﻿using System.Drawing.Imaging;
using System.Web.Mvc;
using MvcCaptcha;

namespace Web.Base.ActionResults
{
    public class CaptchaImageResult : ActionResult
    {
        public string CaptchaKey { get; set; }
        public CaptchaImageResult(string captchaKey)
        {
            CaptchaKey = captchaKey;
        }
        public override void ExecuteResult(ControllerContext context)
        {
            var captcha = new MvcCaptchaImage();
            if (!string.IsNullOrEmpty(CaptchaKey))
            {
                if (context.HttpContext.Session != null)
                    context.HttpContext.Session[CaptchaKey] = captcha.Text.ToLower();
            }
            using (var image = captcha.RenderImage())
            {
                image.Save(context.HttpContext.Response.OutputStream, ImageFormat.Gif);
            }
            context.HttpContext.Response.Cache.SetNoStore();
            context.HttpContext.Response.ContentType = "image/gif";
        }
    }
}